<template>
  <BasicModal v-bind="config" @register="registerModal" :title="currTitle" :height="70"
              wrapClassName="loginSelectModal" v-model:visible="visible">
    <a-form ref="formRef" :model="formState" :rules="rules" v-bind="layout" :colon="false" class="loginSelectForm">
      <!--多租户选择-->
      <a-form-item v-if="isMultiTenant" name="tenantId" :validate-status="validate_status">
        <!--label内容-->
        <template #label>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>请选择登录系统</span>
            </template>
            <a-avatar style="background-color: #87d068" :size="30"> 系统</a-avatar>
          </a-tooltip>
        </template>
        <template #extra v-if="validate_status == 'error'">
          <span style="color: #ed6f6f">请选择登录系统</span>
        </template>

        <!--租户下拉内容-->
        <a-select v-model:value="formState.tenantId" @change="handleTenantChange"
                  placeholder="请选择登录系统" :class="{ 'valid-error': validate_status == 'error' }">
          <template v-for="tenant in tenantList" :key="tenant.id">
            <a-select-option :value="tenant.id">{{ tenant.name }}</a-select-option>
          </template>
        </a-select>
      </a-form-item>

      <!--多部门选择 isMultiDepart false-->
      <a-form-item v-if="false" :validate-status="validate_status1" :colon="false">
        <!--label内容-->
        <template #label>
          <a-tooltip placement="topLeft">
            <template #title>
              <span>您隶属于多部门，请选择登录部门</span>
            </template>
            <a-avatar style="background-color: rgb(104, 208, 203)" :size="30"> 部门</a-avatar>
          </a-tooltip>
        </template>
        <template #extra v-if="validate_status1 == 'error'">
          <span style="color: #ed6f6f">请选择登录部门</span>
        </template>

        <!--部门下拉内容-->
        <a-select v-model:value="formState.orgCode" @change="handleDepartChange"
                  placeholder="请选择登录部门" :class="{ 'valid-error': validate_status1 == 'error' }">
          <template v-for="depart in departList" :key="depart.orgCode">
            <a-select-option :value="depart.orgCode">{{ depart.departName }}</a-select-option>
          </template>
        </a-select>
      </a-form-item>
    </a-form>

    <template #footer>
      <a-button @click="handleSubmit" type="primary">确认</a-button>
    </template>
  </BasicModal>
</template>

<script lang="ts">
import { defineComponent, ref, computed, unref, reactive, UnwrapRef } from "vue";
import { Avatar } from "ant-design-vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { useMessage } from "/@/hooks/web/useMessage";
import { useUserStore } from "/@/store/modules/user";
import { defHttp } from "/@/utils/http/axios";
import { getUserTenants } from "/@/views/system/tenant/tenant.api";
// import { usePermission } from "/@/hooks/web/usePermission";
// import { usePermissionStore } from "/@/store/modules/permission";
// import { useAppStore } from "/@/store/modules/app";

interface FormState {
  orgCode: string | undefined;
  tenantId: number;
}

export default defineComponent({
  name: "loginSelect",
  components: {
    Avatar,
    BasicModal
  },
  emits: ["success", "register"],
  setup(props, { emit }) {
    const userStore = useUserStore();
    const { notification } = useMessage();
    //租户配置
    const isMultiTenant = ref(false);
    const tenantList = ref<any[]>([]);
    const validate_status = ref("");
    //部门配置
    const isMultiDepart = ref(false);
    const departList = ref([]);
    const validate_status1 = ref("");
    //弹窗显隐
    const visible = ref(false);
    //登录用户
    const username = ref("");
    //表单
    const formRef = ref();
    //选择的租户部门信息
    const formState: UnwrapRef<FormState> = reactive({
      orgCode: undefined,
      tenantId: null
    });

    const config = {
      maskClosable: false,
      closable: false,
      canFullscreen: false,
      width: "500px",
      minHeight: 20,
      maxHeight: 20
    };
    //弹窗操作
    const [registerModal, { closeModal }] = useModalInner();

    //当前标题
    const currTitle = computed(() => {
      // if (unref(isMultiDepart) && unref(isMultiTenant)) {
      //   return "请选择租户和部门";
      // } else if (unref(isMultiDepart) && !unref(isMultiTenant)) {
      //   return "请选择部门";
      // } else if (!unref(isMultiDepart) && unref(isMultiTenant)) {
      //   return "请选择登录系统";
      // }
      if (unref(isMultiTenant)) {
        return "请选择登录系统";
      }
    });

    const rules = ref({
      tenantId: [{
        required: unref(isMultiTenant),
        message: "请选择租户",
        trigger: "change",
        type: "number"
      }],
      orgCode: [{ required: unref(isMultiDepart), message: "请选择部门", trigger: "change" }]
    });

    const layout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 18 }
    };

    /**
     * 处理部门情况
     */
    function bizDepart(loginResult) {
      let multi_depart = loginResult.multi_depart;
      //0:无部门 1:一个部门 2:多个部门
      if (multi_depart == 0) {
        notification.warn({
          message: "提示",
          description: `您尚未归属部门,请确认账号信息`,
          duration: 3
        });
        isMultiDepart.value = false;
      } else if (multi_depart == 2) {
        isMultiDepart.value = true;
        departList.value = loginResult.departs;
      } else {
        isMultiDepart.value = false;
      }
    }

    /**
     * 处理租户情况
     */
    function bizTenantList(loginResult) {
      let tenantArr = loginResult.tenantList;
      //console.info("bizTenantList@@ userStore.getTenant = ", userStore.getTenant)
      if (Array.isArray(tenantArr)) {
        if (tenantArr.length === 0) {
          isMultiTenant.value = false;
          userStore.setTenant(formState.tenantId);
        } else if (tenantArr.length === 1) {
          formState.tenantId = tenantArr[0].id;
          isMultiTenant.value = false;
          userStore.setTenant(formState.tenantId);
        } else {
          let userStoreTenantId = userStore.getTenant
          if (userStoreTenantId) {
            const filtered = tenantArr.filter(function(val){
              return val.id === userStoreTenantId;
            });
            //多租户有缓存 - 已配置 - 无需选择框
            if (filtered.length > 0) {
              isMultiTenant.value = false;
              userStore.setTenant(userStoreTenantId);
            } else {
              isMultiTenant.value = true;
            }
          } else {
            //多租户无缓存 - 弹出选择框
            isMultiTenant.value = true;
          }
          tenantList.value = tenantArr;
        }
      } else {
        const result = getUserTenants();
        if (!result.list || result.list.length == 0) {
          return;
        }
        tenantList.value = result.list;
      }
    }

    /**
     * 确认选中的租户和部门信息
     */
    function handleSubmit() {
      if (unref(isMultiTenant) && !formState.tenantId) {
        validate_status.value = "error";
        return false;
      }
      if (unref(isMultiDepart) && !formState.orgCode) {
        validate_status1.value = "error";
        return false;
      }

      //重新获取用户信息和菜单
      //const permissionStore = usePermissionStore();
      const userStore = useUserStore();

      formRef.value.validate()
        .then(() => {
          departResolve()
            .then(() => {
              //console.info("departResolve@@@@", (formState.tenantId))
              userStore.setTenant(formState.tenantId);
              emit("success");
            })
            .catch((e) => {
              console.log("登录选择出现问题", e);
            })
            .finally(() => {
              close();
            });
        }).then(() => {
          //console.info("handleSubmit@@@@切换系统", (formState.tenantId))
          // 重新获取用户信息和菜单
          //userStore.getUserInfoAction();
          //permissionStore.changePermissionCode();
        }).catch((err) => {
          console.log("表单校验未通过error", err);
        });
    }

    /**
     *切换选择部门
     */
    function departResolve() {
      return new Promise<void>((resolve, reject) => {
        if (!unref(isMultiDepart)) {
          resolve();
        } else {
          let params = { orgCode: formState.orgCode, username: unref(username) };
          defHttp.put({ url: "/sys/selectDepart", params }).then((res) => {
            if (res.userInfo) {
              userStore.setUserInfo(res.userInfo);
              resolve();
            } else {
              requestFailed(res);
              userStore.logout();
              reject();
            }
          });
        }
      });
    }

    /**
     * 请求失败处理
     */
    function requestFailed(err) {
      notification.error({
        message: "登录失败",
        description: ((err.response || {}).data || {}).message || err.message || "请求出现错误，请稍后再试",
        duration: 4
      });
    }

    /**
     * 关闭model
     */
    function close() {
      closeModal();
      reset();
    }

    /**
     * 多租户选择窗
     * 1、当前登录用户，是否是多租户
     * 2、选择后，默认进入系统，不再弹出选择框
     * 3、切换后，系统名称改变
     */
    async function show(loginResult) {
      if (loginResult) {
        username.value = userStore.getUserInfo.username;
        await reset();
        await bizTenantList(loginResult);
        if (!unref(isMultiTenant)) {
          emit("success", userStore.getUserInfo);
        } else {
          visible.value = true;
        }
      }
      //登录弹窗完成后，将登录的标识设置成false
      loginResult.isLogin = false;
      //问题：qindl 20223-04-27
      // 1、正常登录，选好公司，然后关闭浏览器，再打开，loginResult = {} 为空
      // 2、loginResult值是通过 userStore.getLoginInfo，获取
      // 3、userStore.getLoginInfo 为什么会为空，没想通
      userStore.setLoginInfo(loginResult);
    }

    /**
     *重置数据
     */
    function reset() {
      tenantList.value = [];
      validate_status.value = "";

      departList.value = [];
      validate_status1.value = "";
    }

    function handleTenantChange(e) {
      validate_status.value = "";
      //多部门与选择系统同步
      if (!isMultiDepart.value) {
        return false;
      }
      let dep = departList.value || [];
      for (let i = 0; i < dep.length; i++) {
        if (dep[i]['tenantId'] == e) {
          formState.orgCode = dep[i]['orgCode']
        }
      }
    }

    function handleDepartChange() {
      validate_status1.value = "";
    }

    return {
      registerModal,
      visible,
      tenantList,
      isMultiTenant,
      validate_status,
      isMultiDepart,
      departList,
      validate_status1,
      formState,
      rules,
      layout,
      formRef,
      currTitle,
      config,
      handleTenantChange,
      handleDepartChange,
      show,
      handleSubmit
    };
  }
});
</script>

<style lang="less" scoped>
.loginSelectForm {
  margin-bottom: -20px;
}

.loginSelectModal {
  top: 10px;
}
</style>
